<%--
    fileName      : addfile.jsp
    author        : linyb
    createDate    : 2016-03-14     
    description   : 上传附件页面
--%>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="ctp-tag" prefix="ctp" %>




<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<ctp:include items='ajaxfileupload,borderlayout,panel,link,toolbar,textfield,button,tabletree,combobox,form,grid,textarea,label,lightlayout,gridlayout,groupbox,message_ex,validator,datepicker,radiogroup,checkboxgroup'/>
		 <script type="text/javascript" src="/js/ctp/ctp/ajaxfileupload/uploadify/swfobject.js"></script>
		 <script type="text/javascript" src="/js/ctp/ctp/ajaxfileupload/uploadify/jquery.uploadify.v2.1.0.js"></script>
		 <script type="text/javascript" src="/js/ctp/ctp/ajaxfileupload/ctp.ui.ajaxfileupload.js"></script>
		
		 
		 <link rel="stylesheet" type="text/css" href="/css/ajaxfileupload/default.css" />
		 <link rel="stylesheet" type="text/css" href="/css/ajaxfileupload/uploadify.css" />
		 <link rel="stylesheet" type="text/css" href="/css/ajaxfileupload/ajaxfileupload.css" />
		
		<title>异步文件上传页面</title>
		<script type='text/javascript' kind='variant'>

		    var tabletreepanel;
		    var dicId = '<ctp:out name="dicId"/>';
			var recId = '<ctp:out name="recId"/>';
			var labelId = '<ctp:out name="labelId"/>';
			var indexId = '<ctp:out name="indexId"/>';
			var businessType = '<ctp:out name="businessType"/>';//businessType 1 消息管理模块
			var filetype = '<ctp:out name="filetype"/>';
			var userId ='<ctp:out name ="sessCtx.user.id"/>';
			
			var dwdicTree;
			
		 	var attachfileUploadPanel;
	        var attachfileUpload;
	        var attachfileUploadGridlayout;
	        var noticeLabel;
	        var tips;
	        var curStatusbar;
	       //来自字典的参数
	        var attSizeDict = '52428800';
	        var attCountDict = '10';
	        var attTotalSizeDict = '104857600';
	        
	      	//设置真正上限的参数；
	        var fileSizeLimited = attSizeDict ? parseInt(attSizeDict) : (1024*1024*50);
	        var fileCountLimited = attCountDict ? parseInt(attCountDict) : 10;
	        var fileTotalSizeLimited = attTotalSizeDict ? parseInt(attTotalSizeDict) : (1024*1024*100);
	        var fileTotalSizeLimitedMB = fileTotalSizeLimited/1024/1024;
	        var fileSizeLimitedMB = fileSizeLimited/1024/1024;

	        var uploadResult = new Array();
	        var fileList = new Array();
	        var queueTotalSize = 0;

	        var gridFileList = $.extend(true,[],parent.ctpMSB.settings.param);

	        var Ext1 = '*.doc;*.docx;*.pdf;*.xls;*.xlsx';
			var Ext2 = '*.jpg;*.jpeg;*.png;*.gif';
			var fileExt ='*.*';
			if(filetype!=''){
				if(filetype==0 || filetype==1 ||filetype==2){
					fileExt = Ext2;
				}
			}
			
		</script>	
	    <script type='text/javascript' kind='event'>
	         function addfileDwdicId(e){
	        	 var _mContext = "addappendixcols.jsp -> addfileDwdicId()";  
		         try{
		         var code=dwdicTree.getCheckedObj()[0].code;
		         var name=dwdicTree.getCheckedObj()[0].name;

		         var tt=attachfileUpload.getSettings();
		         tt.params.fileDwdicName=name;
		         }catch(e){
		        	  ctp.core.log.err(_mContext, e.message);
			         }
		         }
			 
	         function removeFileListByName(fileName){
	            var delIndex = -1;
			    for(var i=0,len2=fileList.length;i<len2;i++){
			       if(fileList[i].obj.name == fileName){
			    	  delIndex = i;
			          break; 
			       } 
				}
				if(delIndex != -1){
					fileList.splice(delIndex,1);
				}
		     }
		     
			 
			 function deleteByName(fileName){
			    for(var i=0,len=fileList.length;i<len;i++){
			       if(fileList[i].obj.name == fileName){
			    	  attachfileUpload.removeFromQueue(fileList[i].id);
			          break; 
			       } 
				}
			    removeFileListByName(fileName);
	         } 

			 
	        function checkFilesExist(){
				var retObj = {isExist: false , retMsg:''};
				for(var i=0,len=fileList.length; i < len; i++){
					var eachIsExist = false; //每个文件的是否已经存在
					var fileName = fileList[i].obj.name;
					for(var j=0, elen=gridFileList.length; j< elen; j++){
						if(gridFileList[j].fileName == fileName){
							eachIsExist = true;
							break;
						}
					}
					//如果文件检查有错误，添加错误添加文件已经存在信息
				    if(eachIsExist == true){
				    	retObj.isExist = true;
				    	retObj.retMsg += ('“'+fileName+'”在文件列表中已经存在，上传保存后将更新此文件<br/>');
				    }
				}
				return retObj;
		    }
			 
			function checkEachFile(){
				var retObj = {};
				retObj.retFlag = true;
				retObj.retMsg = '';
				for(var i=0,len=fileList.length; i < len; i++){
					var eachFileFlag = true; //每个文件的是否错误判断标志，默认是正确的
					var fileName = fileList[i].obj.name;
					var tempMsg = '';
					var errIndex = 1;
					var strPrefixOptional = '&nbsp;&nbsp;&nbsp;&nbsp;';	//错误提示点缩进

					//文件名长度校验
					if(fileName.length > 100){
						tempMsg += (strPrefixOptional + errIndex + '. 文件的文件名长度不能超过100个字符(中文1个字符)<br/>');
						eachFileFlag = false;
						errIndex++;
					}
					
					//特殊字符校验提示
					var patten = new RegExp('[:^\'/\\\";,$%*<>&?|]','g');
					if(patten.test(fileName)){
						tempMsg += (strPrefixOptional + errIndex +'. 文件的文件名中请不要含有英文半角符号的:^\'/\\\";,$%*<>&?|否则系统会控制无法上传文件<br/>');
						eachFileFlag = false;
						errIndex++;
					}
					
					//选中的文档大小超过限制提示
				    if(fileList[i].obj.size > attachfileUpload.getSettings().sizeLimit){
				    	tempMsg += (strPrefixOptional + errIndex +'. 文件的大小不能超过'+fileSizeLimitedMB+'MB<br/>');
				    	eachFileFlag = false;
				    	errIndex++;
				    }
				    
					//选中的文档大小小于等于零，将其从导入文档列表中删除
				    if(fileList[i].obj.size <= 0){
				    	tempMsg += (strPrefixOptional + errIndex +'. 文件内容不能为空<br/>');
				    	eachFileFlag = false;
				    	errIndex++;
				    }
				    
				    //如果文件检查有错误，添加错误前缀（文件名）
				    if(eachFileFlag == false){
				    	retObj.retFlag = false;
				    	retObj.retMsg += ('<font color="#000000">“'+fileName+'”有如下错误：</font><br/>'+tempMsg);
				    }
				}
				return retObj;
			}
	    </script>
      <script type='text/javascript' kind='ui'>
      var fileurl= '<ctp:url href="fileUpload/fileuploadnew.flowc" flowActionName="addindexfile"/>';
	        $(window).load(function(){
		       
	            attachfileUpload = new ctp.ui.ajaxfileupload({
					id: 'attachfileUpload',
					auto: false,	
					multi: true,  //是否多文件上传
					simUploadLimit:100, 		//允许同时上传文件个数；
					sizeLimit: '500000000',
					fileExt : fileExt,
					width: '460px',
					browserBtnText: '浏览',
					uploadBtn: true,
					uploadBtnText: '上传',
					clearBtn: true,
					clearBtnText: '清空',
					flowcUrl: '<ctp:url href="fileUpload/fileuploadnew.flowc"/>',
				    flowActionName: 'addindexfile',
					params:{'recId':recId,
						    'labelId':labelId,
						    'indexId':indexId,
						    'businessType':businessType,
						    'saveType':'1',
						    'userId':userId,
						    'fileDwdicId':  '',
						    'fileDwdicName':''
							  },
					onSelect: function (fileId, fileObj){
	            	    fileList.push({id:fileId, obj:fileObj});
					},
					onSelectOnce: function (data){
						noticeLabel.setText('');
						queueTotalSize = data.allBytesTotal;
						if((fileList.length + 1) > attachfileUpload.settings.queueSizeLimit){
						   noticeLabel.setText('<font color="#FF0000">提示：队列已达上传上限'+attachfileUpload.settings.queueSizeLimit+'个文件，不能再添加上传文件，但可以上传队列中的文件</font>');
						   return;
						}
						if(data.filesReplaced > 0){
						   noticeLabel.setText('<font color="#FF0000">你选择了'+data.filesReplaced+'个上传队列中存在的同名文件，系统已经自动替换了这些文件</font>');
						   return;
						}
						var checkResult = checkFilesExist();
						if(checkResult.isExist == true){
							noticeLabel.setText('<font color="#FF0000">'+checkResult.retMsg+'</font>');
							return;
						}
					},
					onUpload: function(){
						noticeLabel.setText('');
						if(fileList.length==0){
						  noticeLabel.setText('<font color="#FF0000">请选择一个文件</font>');
						  return false;
						}
						//因异步控件，大于选择文件数的限制时，是否选不中文件的，因此提示应该是不会出现的
						if(fileList.length > fileCountLimited){
							noticeLabel.setText('<font color="#FF0000">一次最多只能上传'+fileCountLimited+'个文件</font>');
							return false;
						}
						if(queueTotalSize > fileTotalSizeLimited){
							   noticeLabel.setText('<font color="#FF0000" >所有文件的总大小超过文件上传限定的总大小'+fileTotalSizeLimitedMB+'MB</font><br/>');
							   return false;
						}
						var checkResult = checkEachFile();
						if(checkResult.retFlag == false){
							noticeLabel.setText('<font color="#FF0000">'+checkResult.retMsg+'</font>');
							return false;
						}
						curStatusbar.showTime({opTimeValue : 0, boolScreen:true});
					},
					onRemove: function(fileID, fileObj,data){
						try{
							queueTotalSize = data.allBytesTotal;
							noticeLabel.setText('');
							if(fileObj && fileObj.name){
								removeFileListByName(fileObj.name);
							}
						}catch(e){
							noticeLabel.setText('删除文件错误,原因：' + e.message);
						}
	                },
					onClearQueue: function(){
	                	queueTotalSize = 0;
	    				noticeLabel.setText('');
	    				fileList = new Array();
					},
					onComplete: function(fileID, fileObj, response, data){
						try{
						    var jsonRetVal = $.parseJSON(response);
							if(jsonRetVal[0].operateResult){
							  uploadResult.push({
								  				 operateResult: jsonRetVal[0].operateResult,
								  				 notice: (jsonRetVal[0].notice ? jsonRetVal[0].notice : ''),
								  				 fileExt:  (jsonRetVal[0].fileExt ? jsonRetVal[0].fileExt  : ''),
								  		         attId:  (jsonRetVal[0].attId ? jsonRetVal[0].attId  : ''),
								  		         fileName: (jsonRetVal[0].fileName ? jsonRetVal[0].fileName : fileObj.name),
								  		         fileSize: (jsonRetVal[0].fileSize ? jsonRetVal[0].fileSize : fileObj.size),
								  		         createTime: (jsonRetVal[0].createTime ? jsonRetVal[0].createTime : '')
									  		       });
					       }else{
					    	  uploadResult.push({
					  				 operateResult: 'error',
					  				 notice: (jsonRetVal[0].errorMsg ? jsonRetVal[0].errorMsg : ''),
					  		         attId:  '',
					  		         fileName: fileObj.name,
					  		         fileSize:'',
					  		         createTime: ''
					  		       });
						    }
						}catch(e){
							uploadResult.push({
				  				 operateResult: 'error',
				  				 notice: e.message,
				  		         attId:  '',
				  		         fileName: fileObj.name,
				  		         fileSize:'',
				  		         createTime: ''
				  		    });
						}
					},
					onError: function(fileID, fileObj, errorObj){
	                    uploadResult.push({
			  				 operateResult: 'error',
			  				 notice: errorObj.info,
			  		         attId:  '',
			  		         fileName: fileObj.name,
			  		         fileSize:'',
			  		         createTime: ''
			  		       });
	                },
					onAllComplete:function(data){
	                	curStatusbar.endShow(true);
	                	queueTotalSize = 0;
	                	fileList = new Array();
	                	noticeLabel.setText('');
	                	attachfileUpload.clear();

						var retFlag = 'success';
						var retMsg = '';
						var docList = new Array();
						for(var i=0,len=uploadResult.length; i < len; i++){
							var op_res = uploadResult[i].operateResult;
							if(op_res == 'success'){
								docList.push({
						 		  'attId': uploadResult[i].attId,
								  'fileName': uploadResult[i].fileName,
								  'fileSize': uploadResult[i].fileSize,
								  'createTime': uploadResult[i].createTime
								});
							}else if(op_res == 'warning'){
								retFlag = 'warning';
								retMsg += uploadResult[i].notice;
						    }else if(op_res == 'error'){
						    	retFlag = 'warning';
						    	retMsg += uploadResult[i].fileName + '上传出错; 原因：'+uploadResult[i].notice + '！<br/>'
							}
						}
						//清除结果集合
						uploadResult = new Array();
						var retObj = {};
						retObj.flag = retFlag;
						retObj.notice = retMsg;
						retObj.docList = docList;
						parent.ctpMSB.doHandler(retObj,true);
					}
				});
	
	            tips = new ctp.ui.label({
	            	  id: 'importtips',
	           		  width: '460px',
	           		  textAlign: 'left',
	           		  text: '<font color="#FF0000" >提示：每次最多上传'+fileCountLimited+'个文件，每个文件不能超过'+fileSizeLimitedMB+'MB，文件的总大小不超过'+fileTotalSizeLimitedMB+'MB</font>'				   
	           	});
	               
	            noticeLabel = new ctp.ui.label({
	            	  id: 'noticeLabel',
	           		  width: '460px',
	           		  textAlign: 'left',
	           		  text: ''				   
	           	});
	           	
				attachfileUploadGridlayout = new ctp.ui.gridlayout({
			        id: 'attachfileUploadGridlayout',
			        width: '98%',
			        height: '100%',
			        align: 'center',
			        cols: 1,
			        colSpace: 2,
			        defaults: {align: 'center'},
			        items: [
							[{element: tips,align: 'center'}],
			                [{element: attachfileUpload,align: 'center'}],
			                [{element: noticeLabel,align: 'center'}]
			        ]
			    });
			    
				attachfileUploadPanel = new ctp.ui.panel({
	                id: 'attachfileUploadPanel',
	                title: '',
	                style:'none',
	                collapsible: false,
	                items: [attachfileUploadGridlayout]
	            });
	            borderlayout = new ctp.ui.borderlayout({
	            	 type: "1C", 
	                center__items:[attachfileUploadPanel],
	                renderTo:'body'
	           }); 	
	            curStatusbar = new ctp.ui.statusbar( {id : 'curStatusbar',isVisible:false,renderTo : $('body')});
	        });
        </script>
	</head>
	<body>
	<input type="hidden" id='fileDwdicId' name="fileDwdicId">
    <input type="hidden" id='fileDwdicName' name="fileDwdicName">
	</body>
</html>

